const mongoose = require('mongoose');

const Cate= require('../model/cate.model');

//zeng
exports.create = function (req,res,next){
    const cate = new Cate(req.body);//实例化对象，req.body代表是post的数据提交，参数从body中获取
    cate.save().then(data=>{
        res.json(data);//进行数据保存，保存后数据以json格式进行输出。
    })
}
//修改
exports.update = function(req,res,next){
    const id = req.params.id;
    Cate.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
        res.json(data);
    })
}
// // 删除
exports.remove = function(req,res,next){
    var id = req.params.id;
    var ids = [];
    Cate.findOne({_id : id},function(err,doc){
        if(doc){
            ids = [doc._id]
            doc.getChildren(function(err,rows){
                //console.log(rows);
                var rowsLength=rows.length;
                for(var i=0;i<rowsLength;i++){
                    ids.push(rows[i]._id);
                }
                //console.log(ids)
                Cate.remove({_id : {$in : ids}}).then(data=>{
                    res.json({message:'删除成功'})
                });
            })
        }
    })
}
//查询
function reverseTree(data,pid){
    var result  = [],
    temp;
    var data = JSON.parse(JSON.stringify(data));
    console.log(data)
    for(var i in data){
        if(data[i].parentId === pid){
            result.push(data[i]);
            temp = reverseTree(data,data[i]._id);
            if(temp.length > 0){
               data[i].children = temp;
            }
        }
    }
    return result;
}

exports.list = function(req,res,next){
    var type = req.params.type;
    Cate.find({type:type},function(err,data){
        var rpTree = reverseTree(data,null);
        res.json(rpTree);
    })
}